import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import App from './App.vue'
import router from './router/index'
import { authAPI } from './api/index'

const app = createApp(App)

// 注册所有Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(ElementPlus)
app.use(router)
app.mount('#app')

// 定时刷新token任务
const startTokenRefreshTask = () => {
  // 每24小时执行一次（24 * 60 * 60 * 1000 = 86400000毫秒）
  setInterval(async () => {
    try {
      const retoken = localStorage.getItem('retoken')
      if (retoken) {
        const response = await authAPI.refreshToken(retoken)
        if (response.success) {
          // 更新token
          localStorage.setItem('token', response.data.token)
          console.log('Token自动刷新成功')
        } else {
          console.error('Token自动刷新失败:', response.message)
          // 刷新失败，清除本地存储，跳转到登录页
          localStorage.removeItem('token')
          localStorage.removeItem('retoken')
          localStorage.removeItem('userInfo')
          window.location.href = '/login'
        }
      }
    } catch (error) {
      console.error('Token自动刷新异常:', error)
      // 异常情况，清除本地存储，跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('retoken')
      localStorage.removeItem('userInfo')
      window.location.href = '/login'
    }
  }, 24 * 60 * 60 * 1000) // 24小时
}

// 启动定时任务
startTokenRefreshTask()